package com.day09;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

public class ComboBoxFrame extends JFrame {
    private static final int WINDOW_WIDTH = 640;
    private static final int WINDOW_HEIGHT = 640;

    private JComboBox<String> cb;
    private JTextField jtf;
    private JButton btn;

    public ComboBoxFrame() {
        initComponent();
        addComponent();
        addListener();
        initWindows();

    }

    private void initComponent() {
//        String[] datas = {"江苏省", "浙江省", "山东省"};
        List<Province> datas = new ArrayList<>();
        Province p1 = new Province(1, "江苏省");
        Province p2 = new Province(2, "浙江省");
        Province p3 = new Province(1, "山东省");
        datas.add(p1);
        datas.add(p2);
        datas.add(p3);
        cb = new JComboBox(datas.toArray());
        jtf = new JTextField(20);
        btn = new JButton("动态操作");

    }

    private void addComponent() {
        this.setLayout(new FlowLayout());
        this.add(cb);
        this.add(jtf);
        this.add(btn);

    }

    private void addListener() {
        cb.addItemListener(
                new ItemListener() {
                    @Override
                    public void itemStateChanged(ItemEvent e) {
                        Province prov = (Province) cb.getSelectedItem();
                        jtf.setText(prov.getName());
                    }
                }
        );
        btn.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int index = cb.getSelectedIndex();
//                        String prov = (String) cb.getSelectedItem();
                        cb.removeItemAt(index);
                    }
                }
        );

    }

    private void initWindows() {
        this.setTitle("下拉框");
        this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new ComboBoxFrame();
    }

    class Province {
        private int id;
        private String name;

        public Province(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public Province() {
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return this.name;
        }
    }
}
